package org.gd136.ce.listener;

import org.gd136.ce.manager.RM;

import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.NinePatch;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Touchable;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.utils.NinePatchDrawable;
import com.badlogic.gdx.utils.Align;

public class ButtonListener extends InputListener {

	Image pic;
	Runnable run;
	int offX = 16;
	int offY = 10;

	public ButtonListener(Runnable run) {
		this.run = run;
		NinePatch np = new NinePatch(RM.loadGetTexture("ui/yes_no_mask.png"),
				offX, offX, offX, offX);
		pic = new Image(new NinePatchDrawable(np));
		pic.setOrigin(Align.center);
		pic.setTouchable(Touchable.disabled);
	}

	public static ButtonListener create(Runnable run) {
		return new ButtonListener(run);
	}

	boolean isIn = false;

	@Override
	public void enter(InputEvent event, float x, float y, int pointer,
			Actor fromActor) {
		pic.clearActions();
		isIn = true;
		Actor src = event.getTarget();
		Group parent = src.getParent();
		float height = src.getHeight() + offY * 2;
		pic.setHeight(height);
		if (parent != null && parent != pic.getParent()) {
			parent.addActor(pic);
			pic.setPosition(src.getX() + src.getWidth() / 2,
					src.getY() + src.getHeight() / 2, Align.center);
			pic.setZIndex(src.getZIndex() + 1);
		}
		pic.addAction(Actions.sequence(Actions.visible(true), Actions.parallel(
				Actions.sizeTo(src.getWidth() + offX * 2, height, 0.1f),
				Actions.moveTo(src.getX() - offX, src.getY() - offY, 0.1f))));
		src.addAction(Actions.color(Color.YELLOW, 0.2f));
	}

	@Override
	public void exit(InputEvent event, float x, float y, int pointer,
			Actor toActor) {
		pic.clearActions();
		isIn = false;
		pic.setColor(Color.WHITE);
		Actor src = event.getTarget();
		src.addAction(Actions.color(Color.WHITE, 0.2f));
		float height = src.getHeight() + offY * 2;
		pic.setHeight(height);
		pic.addAction(Actions.sequence(Actions.parallel(
				Actions.sizeTo(offX * 2, height, 0.1f),
				Actions.moveTo(src.getX() + src.getWidth() / 2 - offX,
						src.getY() - offY, 0.1f)), Actions.visible(false)));
	}

	@Override
	public boolean touchDown(InputEvent event, float x, float y, int pointer,
			int button) {
		pic.clearActions();
		pic.setColor(Color.RED);
		return true;
	}

	@Override
	public void touchUp(InputEvent event, float x, float y, int pointer,
			int button) {
		pic.setColor(Color.WHITE);
		if (isIn && run != null) {
			run.run();
		}
	}

}
